<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- 摄像头位置查询 -->
      <el-form-item label="摄像头位置" prop="deviceSn">
        <el-select
          v-model="queryParams.deviceSn"
          placeholder="请选择摄像头位置"
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="device in deviceOptions"
            :key="device.sn"
            :label="device.location"
            :value="device.sn"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="人员类别" prop="category">
        <el-select v-model="queryParams.category" placeholder="请选择人员类别" clearable>
          <el-option
            v-for="dict in dict.type.category"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="queryParams.gender" placeholder="请选择性别" clearable>
          <el-option
            v-for="dict in dict.type.gender"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="身份证号" prop="idCardNo">
        <el-input
          v-model="queryParams.idCardNo"
          placeholder="请输入身份证号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="身份标识" prop="identity">
        <el-select v-model="queryParams.identity" placeholder="请选择身份标识" clearable>
          <el-option
            v-for="dict in dict.type.identity"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="最后出现时间" prop="lastAppearTime">
        <el-date-picker clearable
          v-model="queryParams.lastAppearTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择最后出现时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ry/staff:staff:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ry/staff:staff:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ry/staff:staff:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ry/staff:staff:export']"
        >导出</el-button>
      </el-col>
      <!-- 添加批量AI分析按钮 -->
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-magic-stick"
          size="mini"
          :disabled="multiple"
          @click="handleBatchAIAnalyze"
        >批量AI分析</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="staffList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="序号" align="center" prop="id" /> -->
      <el-table-column label="姓名" align="center" prop="name" />
      <!-- <el-table-column label="摄像头位置" align="center" prop="deviceLocation" /> -->
      <el-table-column label="人员类别" align="center" prop="category">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.category" :value="scope.row.category"/>
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center" prop="gender">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.gender" :value="scope.row.gender"/>
        </template>
      </el-table-column>
      <el-table-column label="年龄" align="center" prop="age" />
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="身份证号" align="center" prop="idCardNo" />
      <el-table-column label="身份标识" align="center" prop="identity">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.identity" :value="scope.row.identity"/>
        </template>
      </el-table-column>
      <el-table-column label="人脸照片路径" align="center" prop="facePhoto" width="100">
        <template slot-scope="scope">
          <el-popover
            placement="right"
            trigger="hover"
            width="300"
          >
            <div>
              <img :src="scope.row.facePhoto" style="max-width: 100%; max-height: 300px;" />
              <p v-if="scope.row.deviceLocation">设备位置：{{ scope.row.deviceLocation }}</p>
            </div>
            <image-preview slot="reference" :src="scope.row.facePhoto" :width="50" :height="50"/>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="微信用户唯一标识" align="center" prop="openid" />
      <el-table-column label="备注信息" align="center" prop="remark" />
      <el-table-column label="最后出现时间" align="center" prop="lastAppearTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastAppearTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ry/staff:staff:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ry/staff:staff:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 修改后的对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <!-- 左列 -->
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名" />
            </el-form-item>

            <!-- 修改为多选设备 -->
            <el-form-item label="摄像头位置" prop="deviceIds">
              <el-select
                v-model="form.deviceIds"
                multiple
                filterable
                default-first-option
                placeholder="请选择摄像头位置（可多选）"
                style="width: 100%"
              >
                <el-option
                  v-for="device in deviceOptions"
                  :key="device.sn"
                  :label="device.location"
                  :value="device.sn"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="人员类别" prop="category">
              <el-select v-model="form.category" placeholder="请选择人员类别" style="width:100%">
                <el-option
                  v-for="dict in dict.type.category"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="form.gender">
                <el-radio
                  v-for="dict in dict.type.gender"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="年龄" prop="age">
              <el-select v-model="form.age" placeholder="请选择年龄" style="width:100%">
                <el-option
                  v-for="age in ageOptions"
                  :key="age"
                  :label="age"
                  :value="age">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>

          <!-- 右列 -->
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCardNo">
              <el-input v-model="form.idCardNo" placeholder="请输入身份证号" />
            </el-form-item>

            <el-form-item label="身份标识" prop="identity">
              <el-select v-model="form.identity" placeholder="请选择身份标识" style="width:100%">
                <el-option
                  v-for="dict in dict.type.identity"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="人脸照片" prop="facePhoto">
              <image-upload v-model="form.facePhoto" :limit="1" />
            </el-form-item>

            <el-form-item label="备注信息" prop="remark">
              <el-input
                v-model="form.remark"
                placeholder="请输入备注信息"
                type="textarea"
                :rows="2"
              />
            </el-form-item>

            <el-form-item label="最后出现时间" prop="lastAppearTime">
              <el-date-picker
                v-model="form.lastAppearTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期时间"
                style="width:100%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 批量AI分析对话框 -->
    <el-dialog :title="batchAIAnalyzeDialogTitle" :visible.sync="batchAIAnalyzeDialogVisible" width="1600px" append-to-body
              :close-on-click-modal="false">
      <el-row gutter="20">
        <!-- 左边内容 -->
        <el-col :span="12">
          <el-form :model="batchAIAnalyzeForm" ref="batchAIAnalyzeForm" label-width="80px">
            <el-form-item label="AI结果">
              <el-input
                v-model="batchAIAnalyzeForm.result"
                type="textarea"
                :rows="6"
                placeholder="AI分析结果将显示在这里"
                ref="batchAIResultInput"
              ></el-input>
            </el-form-item>
          </el-form>
        </el-col>

        <!-- 右边内容 -->
        <el-col :span="12">
          <el-form :model="batchAIAnalyzeForm" ref="batchAIAnalyzeForm" label-width="80px" style="margin-top: 20px;">
            <el-form-item label="提示词">
              <el-input
                v-model="batchAIAnalyzeForm.prompt"
                type="textarea"
                :rows="4"
                placeholder="请输入AI分析的提示词，如：请根据员工ID123,456的工作记录，生成批量分析报告。"
              ></el-input>
              <el-button type="primary" size="mini" style="margin-top: 8px; float: right;"
                        @click="sendBatchAIAnalyzeRequest" :loading="batchAIAnalyzeLoading">确定
              </el-button>
            </el-form-item>
            <el-form-item>
              <div style="margin-top: 10px;">
                <el-tag
                  v-for="tag in quickPromptTagsBatch"
                  :key="tag.label"
                  effect="plain"
                  size="small"
                  style="margin-right: 10px; cursor: pointer;"
                  @click="handleTagClickBatch(tag.value)"
                >
                  {{ tag.label }}
                </el-tag>
              </div>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelBatchAIAnalyzeDialog">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStaff, getStaff, delStaff, addStaff, updateStaff } from "@/api/ry/staff/staff"
import { listDevice } from "@/api/student/device/device"; // 设备API
// 引入员工批量AI分析API（请确保后端已实现）
import { streamBatchAnalyzeStaffAI } from "@/api/ry/staff/staff";

export default {
  name: "Staff",
  dicts: ['category', 'identity', 'gender'],
  data() {
    return {
      deviceOptions: [], // 设备列表
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工作人员信息表格数据
      staffList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数（统一使用deviceSn）
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        category: null,
        gender: null,
        phone: null,
        idCardNo: null,
        identity: null,
        lastAppearTime: null,
        deviceSn: null, // 统一使用deviceSn
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deviceIds: [
          { required: true, message: "请至少选择一个设备", trigger: "change" },
          { type: 'array', min: 1, message: '请至少选择一个设备', trigger: 'change' }
        ],
        name: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        age: [
          { required: true, message: "请选择年龄", trigger: "change" }
        ]
      },
      // 批量AI分析对话框相关数据
      batchAIAnalyzeDialogVisible: false,
      batchAIAnalyzeDialogTitle: '批量AI分析',
      batchAIAnalyzeLoading: false,
      batchAIAnalyzeController: null,
      batchAIAnalyzeForm: {
        prompt: '',
        result: '',
      },
      quickPromptTagsBatch: [
        { label: '生成员工画像', value: '请对以下员工{staffIds}进行员工画像分析，包括工作表现、技能等。' },
        { label: '推荐发展计划', value: '请根据员工{staffIds}的特点，推荐个性化的发展计划。' },
        { label: '工作风险评估', value: '请对员工{staffIds}进行工作风险评估，识别潜在问题。' },
      ],
      ageOptions: [], // 新增年龄选项数组
    }
  },
  created() {
    this.getList();
    this.getDeviceList(); // 加载设备列表
    this.generateAgeOptions(); // 新增：生成年龄选项
  },
  watch: {
    'batchAIAnalyzeForm.result': function (newVal, oldVal) {
      this.$nextTick(() => {
        const textarea = this.$refs.batchAIResultInput ? this.$refs.batchAIResultInput.$refs.textarea : null;
        if (textarea) {
          textarea.scrollTop = textarea.scrollHeight;
        }
      });
    }
  },
  methods: {
    // 获取设备列表
    getDeviceList() {
      listDevice({
        pageNum: 1,
        pageSize: 1000
      }).then(response => {
        this.deviceOptions = response.rows;
      });
    },

    // 查询工作人员信息列表
    getList() {
      this.loading = true
      listStaff(this.queryParams).then(response => {
        this.staffList = response.rows.map(staff => {
          // 兼容处理：优先使用deviceSn，其次使用deviceId
          const deviceSn = staff.deviceSn || staff.deviceId;
          const device = this.deviceOptions.find(d => d.sn === deviceSn);
          return {
            ...staff,
            deviceLocation: device ? device.location : "未知位置"
          };
        });
        this.total = response.total
        this.loading = false
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        pid: null,
        name: null,
        category: null,
        gender: null,
        age: null,
        phone: null,
        idCardNo: null,
        identity: null,
        facePhoto: null,
        openid: null,
        remark: null,
        lastAppearTime: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
        deviceIds: [] // 初始化设备ID数组
      }
      this.resetForm("form")
    },

    // 搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    // 重置按钮操作
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    // 新增按钮操作
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加工作人员信息"
    },

    // 修改按钮操作
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getStaff(id).then(response => {
        const data = response.data;

        // 兼容处理：将deviceId转为deviceIds数组
        if (data.deviceId && !data.deviceIds) {
          data.deviceIds = [data.deviceId];
        }

        this.form = data;
        this.open = true
        this.title = "修改工作人员信息"
      })
    },

    // 提交按钮
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 提交前处理设备ID
          const formData = { ...this.form };

          // 如果后端需要单个设备ID，使用第一个设备ID
          if (formData.deviceIds && formData.deviceIds.length > 0) {
            formData.deviceSn = formData.deviceIds[0];
          }

          if (formData.id != null) {
            updateStaff(formData).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addStaff(formData).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },

    // 删除按钮操作
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除工作人员信息编号为"' + ids + '"的数据项？').then(function() {
        return delStaff(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },

    // 导出按钮操作
    handleExport() {
      this.download('ry/staff/staff/export', {
        ...this.queryParams
      }, `staff_${new Date().getTime()}.xlsx`)
    },

    // 新增：生成年龄选项
    generateAgeOptions() {
      const ages = [];
      for (let i = 1; i <= 100; i++) {
        ages.push(i);
      }
      this.ageOptions = ages;
    },

    // 批量AI分析按钮操作
    handleBatchAIAnalyze() {
      this.batchAIAnalyzeDialogVisible = true;

      // 获取选中的员工名称列表
      const selectedStaffNames = this.ids.map(id => {
        const staff = this.staffList.find(s => s.id === id);
        return staff ? staff.name : `ID:${id}`;
      });
      this.batchAIAnalyzeForm.prompt = `请对员工: ${selectedStaffNames.join(', ')} 进行批量AI分析。`;
      this.batchAIAnalyzeForm.result = ''; // 清空上一次的分析结果
    },

    // 发送批量AI分析请求
    async sendBatchAIAnalyzeRequest() {
      if (!this.batchAIAnalyzeForm.prompt) {
        this.$modal.msgWarning("请输入AI分析提示词！");
        return;
      }
      if (this.batchAIAnalyzeLoading) return;

      this.batchAIAnalyzeLoading = true;
      this.batchAIAnalyzeForm.result = '';
      if (this.batchAIAnalyzeController) this.batchAIAnalyzeController.abort();
      this.batchAIAnalyzeController = new AbortController();

      try {
        const reader = await streamBatchAnalyzeStaffAI({
          staffIds: this.ids,
          prompt: this.batchAIAnalyzeForm.prompt
        }, this.batchAIAnalyzeController.signal);

        const decoder = new TextDecoder('utf-8');
        let done = false;
        let aiText = '';
        while (!done) {
          const {value, done: doneReading} = await reader.read();
          done = doneReading;
          if (value) {
            aiText += decoder.decode(value, {stream: !done});
            this.batchAIAnalyzeForm.result = aiText;
          }
        }
      } catch (err) {
        if (err.name === 'AbortError') {
          console.log('批量AI分析请求已取消');
        } else {
          this.$message.error('批量AI分析失败');
          console.error('批量AI分析错误:', err);
        }
      } finally {
        this.batchAIAnalyzeLoading = false;
        this.batchAIAnalyzeController = null;
      }
    },

    // 取消批量AI分析对话框
    cancelBatchAIAnalyzeDialog() {
      this.batchAIAnalyzeDialogVisible = false;
      if (this.batchAIAnalyzeController) {
        this.batchAIAnalyzeController.abort();
        this.batchAIAnalyzeController = null;
      }
      this.batchAIAnalyzeForm.prompt = '';
      this.batchAIAnalyzeForm.result = '';
    },

    // 处理标签点击事件
    handleTagClickBatch(tagValue) {
      if (this.ids.length === 0) {
        this.$modal.msgWarning("请先选择员工！");
        return;
      }
      // 获取选中的员工名称列表
      const selectedStaffNames = this.ids.map(id => {
        const staff = this.staffList.find(s => s.id === id);
        return staff ? staff.name : `ID:${id}`;
      });
      let finalPrompt = tagValue.replace(/{staffIds}/g, selectedStaffNames.join(', '));
      this.batchAIAnalyzeForm.prompt = finalPrompt;
    }
  }
}
</script>

<style scoped>
/* 添加间距优化 */
.el-form-item {
  margin-bottom: 18px;
}
</style>
